<?php

namespace app\admin\controller\subject;

use app\common\controller\Backend;

/**
 * 课程管理
 */
class Chapter extends Backend
{
    // 当前对象模型
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Subject.Chapter');
    }

    // 查看
    public function index($ids = null)
    {
        //$ids的解释： url 按钮的链接/Ajax事件请求的URL/弹窗链接/选项卡链接，直接function和string类型,此链接会自动在链接后添加ids/{ids},{ids}为当行主键ID，如果需要传递其它字段值，请在URL中使用{字段名}占位即可
        // halt($ids);//课程id
        if ($this->request->isAjax()) {
            // halt($ids);//这里是拿不到的

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }


    // 添加
    public function add($subid = null)
    {
        if ($this->request->isPOST()) {
            $params = $this->request->post("row/a", [], 'trim');
            $params['subid'] = $subid;
            $result = $this->model->save($params);
            if (!$result) {
                $this->error($this->model->getError());
            }

            $this->success();
        }
        return $this->view->fetch();
    }

    
    // 编辑
    public function edit($ids = null)
    {
        $row = $this->model->find($ids);
        if (!$row) {
            $this->error('课程章节不存在');
        }
        if ($this->request->isPOST()) {
            $params = $this->request->post("row/a", [], 'trim');
            $params['id'] = $ids;
            $result = $this->model->isUpdate()->save($params);
            if (!$result) {
                $this->error($this->model->getError());
            }
            if (!empty($params['url']) && $params['url'] != $row['url']) {
                is_file(trim($row['url'], '/')) && unlink(trim($row['url'], '/'));
            }
            $this->success();
        }
        $this->assign('row', $row);
        return $this->view->fetch();
    }

    // 删除
    public function del($ids = null)
    {
        $row = $this->model->all($ids);

        if (!$row) {
            $this->error('课程章节不存在');
        }

        $result = $this->model->destroy($ids);

        if (!$result) {
            $this->error($this->model->getError());
        }

        foreach ($row as $item) {
            is_file(trim($item['url'], '/')) && unlink(trim($item['url'], '/'));
        }

        $this->success();
    }
}
